import React, { useState } from 'react';
import { Upload, Button, message, Card, Typography, List, Tag, Space, Alert, Divider } from 'antd';
import { UploadOutlined, FileExcelOutlined, DeleteOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { useProduct } from '../context/ProductContext';
import { parseExcelFile, parseExcelFileWithImages, convertExcelDataToProducts } from '../utils/excelParser';
import type { UploadFile } from 'antd/es/upload/interface';

const { Title, Text, Paragraph } = Typography;

const ExcelUploader: React.FC = () => {
  const { state, dispatch } = useProduct();
  const { categories } = state;
  const [uploading, setUploading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const handleUpload = async (file: File) => {
    setUploading(true);
    try {
      message.loading('正在解析Excel文件(包含图片)...', 0);
      
      // 优先使用带图片支持的解析器
      let excelDataList;
      try {
        excelDataList = await parseExcelFileWithImages(file);
        console.log('✅ 使用ExcelJS成功解析文件(支持图片)');
      } catch (error) {
        console.warn('ExcelJS解析失败，回退到XLSX解析:', error);
        excelDataList = await parseExcelFile(file);
        console.log('✅ 使用XLSX成功解析文件(不支持图片)');
      }
      
      // 转换为产品数据
      const newCategories = convertExcelDataToProducts(excelDataList);
      
      // 合并现有分类和新分类
      const mergedCategories = [...categories];
      
      newCategories.forEach(newCategory => {
        const existingIndex = mergedCategories.findIndex(c => c.id === newCategory.id);
        if (existingIndex >= 0) {
          // 合并现有分类
          const existingCategory = mergedCategories[existingIndex];
          newCategory.subcategories.forEach(newSubcategory => {
            const existingSubIndex = existingCategory.subcategories.findIndex(s => s.id === newSubcategory.id);
            if (existingSubIndex >= 0) {
              // 替换现有子分类
              existingCategory.subcategories[existingSubIndex] = newSubcategory;
            } else {
              // 添加新子分类
              existingCategory.subcategories.push(newSubcategory);
            }
          });
        } else {
          // 添加新分类
          mergedCategories.push(newCategory);
        }
      });
      
      dispatch({ type: 'SET_CATEGORIES', payload: mergedCategories });
      
      message.destroy();
      message.success(`成功解析Excel文件: ${file.name}`);
      
      // 添加到文件列表
      setFileList(prev => [...prev, {
        uid: Date.now().toString(),
        name: file.name,
        status: 'done',
        response: `解析成功: ${newCategories.length} 个分类`,
      }]);
      
    } catch (error) {
      console.error('解析Excel文件失败:', error);
      message.destroy();
      message.error(`解析Excel文件失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setUploading(false);
    }
  };

  const uploadProps = {
    name: 'file',
    multiple: true,
    accept: '.xlsx,.xls',
    beforeUpload: (file: File) => {
      // 检查文件类型
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                     file.type === 'application/vnd.ms-excel' ||
                     file.name.endsWith('.xlsx') || 
                     file.name.endsWith('.xls');
      
      if (!isExcel) {
        message.error('只能上传Excel文件(.xlsx, .xls)');
        return false;
      }
      
      // 检查文件大小 (限制为10MB)
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        message.error('文件大小不能超过10MB');
        return false;
      }
      
      handleUpload(file);
      return false; // 阻止自动上传
    },
    fileList: [],
    showUploadList: false,
  };

  const handleRemoveFile = (index: number) => {
    setFileList(prev => prev.filter((_, i) => i !== index));
  };

  const clearAllFiles = () => {
    setFileList([]);
    dispatch({ type: 'SET_CATEGORIES', payload: [] });
    message.success('已清空所有数据');
  };

  return (
    <div style={{ padding: '24px' }}>
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        {/* 标题 */}
        <div>
          <Title level={3}>Excel文件管理</Title>
          <Text type="secondary">
            上传Excel文件来导入产品数据。每个Excel文件代表一个产品大类，每个工作表代表一个小类。
          </Text>
        </div>

        {/* Excel格式说明 */}
        <Alert
          message="Excel文件格式要求"
          description={
            <div>
              <Paragraph style={{ marginBottom: '8px' }}>
                <Text strong>重要：</Text>请确保您的Excel文件按以下格式组织数据：
              </Paragraph>
              <ul style={{ marginBottom: '12px', paddingLeft: '20px' }}>
                <li><Text strong>第一行：</Text>第一列可以为空或写"参数名"，其他列为产品名称</li>
                <li><Text strong>从第二行开始：</Text>第一列为参数名称，其他列为该参数在对应产品中的值</li>
                <li><Text strong>每列代表一个产品</Text>，每行代表一个产品参数</li>
                <li><Text strong>🖼️ 图片支持：</Text>Excel中的图片会自动转换为base64格式并在对比中显示</li>
              </ul>
              <div style={{ 
                backgroundColor: '#f6f8fa', 
                padding: '12px', 
                borderRadius: '4px',
                fontFamily: 'monospace',
                fontSize: '12px',
                marginTop: '8px'
              }}>
                <div>参数名称&nbsp;&nbsp;&nbsp;&nbsp;产品A&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;产品B&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;产品C</div>
                <div>品牌&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;华为&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;小米&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;苹果</div>
                <div>价格&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1000&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;800&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1200</div>
                <div>重量&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;100g&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;120g&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;95g</div>
                <div>外观&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[图片]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[图片]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[图片]</div>
              </div>
              <div style={{ marginTop: '8px' }}>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  💡 提示：图片会自动转换为base64格式，建议图片大小不超过1MB以确保最佳性能
                </Text>
              </div>
            </div>
          }
          type="info"
          icon={<InfoCircleOutlined />}
          showIcon
        />

        {/* 上传区域 */}
        <Upload.Dragger {...uploadProps} style={{ padding: '20px' }}>
          <p className="ant-upload-drag-icon">
            <FileExcelOutlined style={{ fontSize: '48px', color: '#1890ff' }} />
          </p>
          <p className="ant-upload-text">点击或拖拽Excel文件到此区域上传</p>
          <p className="ant-upload-hint">
            支持单个或批量上传。支持.xlsx和.xls格式，文件大小限制10MB
          </p>
        </Upload.Dragger>

        {/* 手动上传按钮 */}
        <div style={{ textAlign: 'center' }}>
          <Upload {...uploadProps}>
            <Button 
              icon={<UploadOutlined />} 
              loading={uploading}
              size="large"
              type="primary"
            >
              {uploading ? '解析中...' : '选择Excel文件'}
            </Button>
          </Upload>
        </div>

        <Divider />

        {/* 已上传文件列表 */}
        {fileList.length > 0 && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
              <Title level={4} style={{ margin: 0 }}>已导入的文件</Title>
              <Button 
                type="link" 
                danger 
                icon={<DeleteOutlined />}
                onClick={clearAllFiles}
              >
                清空所有
              </Button>
            </div>
            <List
              dataSource={fileList}
              renderItem={(item, index) => (
                <List.Item
                  actions={[
                    <Button 
                      type="link" 
                      danger 
                      size="small"
                      onClick={() => handleRemoveFile(index)}
                    >
                      删除
                    </Button>
                  ]}
                >
                  <List.Item.Meta
                    avatar={<FileExcelOutlined style={{ fontSize: '24px', color: '#52c41a' }} />}
                    title={item.name}
                    description={item.response}
                  />
                  <Tag color="success">已导入</Tag>
                </List.Item>
              )}
            />
          </div>
        )}

        {/* 当前数据统计 */}
        {categories.length > 0 && (
          <Card size="small" style={{ backgroundColor: '#f6ffed' }}>
            <Space>
              <Text strong>当前数据统计:</Text>
              <Tag color="blue">{categories.length} 个产品分类</Tag>
              <Tag color="green">
                {categories.reduce((total, cat) => total + cat.subcategories.length, 0)} 个子分类
              </Tag>
              <Tag color="orange">
                {categories.reduce((total, cat) => 
                  total + cat.subcategories.reduce((subTotal, sub) => subTotal + sub.products.length, 0), 0
                )} 个产品
              </Tag>
            </Space>
          </Card>
        )}
      </Space>
    </div>
  );
};

export default ExcelUploader; 